﻿using lingopen.IdStrategy;
using lingopen.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Chloe;
using lingopen.AutoMapper;
using lingopen.Entity.System;
using lingopen.Application.Common;
using lingopen.Entity.System;

namespace lingopen.Application.Implements
{
    public class ServersAppService : AdminAppService, IServersAppService
    {
        public PagedData<Sys_Server> GetList(Pagination pagination, string keyword)
        {
            var q = this.DbContext.Query<Sys_Server>().FilterDeleted().WhereIfNotNullOrEmpty(keyword, a => a.Name.Contains(keyword) || a.ECSId.Contains(keyword) || a.PublicIP.Contains(keyword) || a.Description.Contains(keyword));
            q = q.OrderBy(a => a.GroupId).ThenBy(o => o.Name);
            PagedData<Sys_Server> ret = q.TakePageData(pagination);
            return ret;
        }

        public int SetServerAvailable(string id, string userId)
        {
            var q = this.DbContext.Query<Sys_Server>().FilterDeleted().Where(a => a.Id == id).FirstOrDefault();
            if (q != null)
            {
                q.Available = !q.Available;
                this.DbContext.Update(q);
                if (q.Available)
                {
                    AliyunHelper.AddVServerGroupBackendServers(q.GroupId, new List<AliyunHelper.BackendServer>()
                    {
                        new AliyunHelper.BackendServer(){
                            ServerId = q.ECSId,
                            Port=q.Port,
                            Weight = q.Weight
                        }
                    });
                }
                else
                {
                    AliyunHelper.RemoveVServerGroupBackendServers(q.GroupId, new List<AliyunHelper.BackendServer>()
                    {
                        new AliyunHelper.BackendServer(){
                            ServerId = q.ECSId,
                            Port=q.Port
                        }
                    });
                }
                return 1;
            }
            return 0;
        }

        public string DescribeInstanceStatus()
        {
            return AliyunHelper.DescribeInstanceStatus();
        }

    }
}
